<template>
  <div class="app-container">
    <div class="search-box-nav">
      <div class="title">基础信息</div>
      <div class="search-box-form">
        <div class="form-nav">
          <el-form
            ref="queryParams"
            :rules="BasicRules"
            :model="queryParams"
            label-width="100px"
          >
            <div class="search_row">
              <el-row>
                <el-col :span="6">
                  <div class="search_col">
                    <el-form-item label="消费客户:" prop="custId">
                      <el-select
                        v-model="queryParams.custId"
                        placeholder="请选择消费客户"
                        class="w-100"
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="remoteMethod"
                        :loading="loading"
                        @change="SelectCustomer"
                      >
                        <el-option
                          v-for="item in ClientOptions"
                          :key="item.id"
                          :label="item.name + '-' + item.mobile"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>

                <el-col :span="6">
                  <el-form-item label="开房员工:" prop="receiveUserId">
                    <el-select
                      v-model="queryParams.receiveUserId"
                      placeholder="请选择开房员工"
                      class="w-100"
                    >
                      <el-option
                        v-for="item in storeUser"
                        :key="item.userId"
                        :label="item.nickname"
                        :value="item.userId"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <div @click="ConsumeRoom">
                    <el-form-item label="消费房间:" prop="roomParamsStr">
                      <el-input
                        v-model="queryParams.roomParamsStr"
                        :readonly="true"
                      ></el-input>
                      <!-- <el-select
                      v-model="queryParams.roomParams"
                      placeholder="请选择消费房间"
                      class="w-100"
                      multiple
                      filterable
                      @change="changeRoomList"
                    >
                      <el-option
                        v-for="item in roomList"
                        :key="item.roomId"
                        :label="item.name"
                        :value="item.roomId"
                      >
                      </el-option>
                    </el-select> -->
                    </el-form-item>
                  </div>
                </el-col>

                <el-col :span="6">
                  <el-form-item label="开房时间:" prop="orderOpen">
                    <el-date-picker
                      class="w-100"
                      v-model="queryParams.orderOpen"
                      type="datetime"
                      placeholder="选择开房时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label="关单时间:" prop="orderRoomClose">
                    <el-date-picker
                      v-model="queryParams.orderRoomClose"
                      type="datetime"
                      placeholder="选择关单时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      class="w-100"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label="结账时间:" prop="orderClose">
                    <el-date-picker
                      v-model="queryParams.orderClose"
                      type="datetime"
                      class="w-100"
                      placeholder="选择结账时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label="进店方式" prop="inStoreType">
                    <el-select
                      v-model="queryParams.inStoreType"
                      placeholder="请选择进店方式"
                    >
                      <el-option
                        v-for="item in storeWayOptions"
                        :key="item.label"
                        :label="item.value"
                        :value="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label="客户类型" prop="custType">
                    <el-select
                      v-model="queryParams.custType"
                      placeholder="请选择客户类型"
                    >
                      <el-option
                        v-for="item in custTypeOptions"
                        :key="item.label"
                        :label="item.value"
                        :value="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="app-box-nav">
      <el-form
        :model="queryParams"
        ref="orderParams"
        size="small"
        :inline="true"
      >
        <div class="box">
          <div class="title">
            <div class="list">订单信息</div>
            <div class="addConsumption" @click="New">+添加消费</div>
          </div>
          <div></div>
        </div>
      </el-form>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="queryParams.recordingServiceList"
        :border="true"
      >
        <el-table-column prop="roomName" label="消费房间" align="center">
          <template slot-scope="{ row, $index }">
            <div>
              <span v-if="!!row.roomId">{{ row.name }}</span>
              <span v-else style="color: #3080fe" @click="AddRoom($index)"
                >+添加房间</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="contentType" label="消费类型" align="center">
          <template slot-scope="scope">
            {{ contentTypeObj[scope.row.contentType] }}
          </template>
        </el-table-column>
        <el-table-column label="消费内容" prop="contentName" align="center">
        </el-table-column>
        <el-table-column label="服务技师" prop="userName" align="center">
        </el-table-column>
        <el-table-column label="上钟时间" prop="clockTimeUp" align="center">
          <template slot-scope="{ row, $index }" v-if="row.contentType === 'I'">
            <div>
              <span style="color: #3080fe" @click="AddUpTimer($index)">{{
                !!row.clockTimeUp ? row.clockTimeUp : "+添加上钟时间"
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下钟时间" prop="clockTimeDown" align="center">
          <template slot-scope="{ row, $index }" v-if="row.contentType === 'I'">
            <div>
              <span style="color: #3080fe" @click="AddDownTimer($index)">{{
                !!row.clockTimeDown ? row.clockTimeDown : "+添加下钟时间"
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="price">
        </el-table-column>
        <el-table-column label="数量" align="center" prop="contentCount">
        </el-table-column>
        <el-table-column label="优惠信息" align="center" prop="preType">
          <template slot-scope="{ row, $index }">
            <div>
              <div v-if="row.isYh">
                <span style="color: red">-￥{{ row.preMoney }}</span>
                <span
                  style="color: #3080fe; margin-left: 10px"
                  @click="preferentialItemOpen(row, $index)"
                  >修改</span
                >
              </div>
              <div v-if="!row.isYh">
                <span
                  style="color: #3080fe"
                  @click="preferentialItemOpen(row, $index)"
                  >+添加优惠</span
                >
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center" prop="serverPriceSum">
          <template slot-scope="scope">
            <span
              >￥{{
                (
                  Number(scope.row.serverPriceSum) -
                  Number(!!scope.row.preMoney ? scope.row.preMoney : 0)
                ).toFixed(2)
              }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          class-name="small-padding fixed-width"
          align="center"
        >
          <template slot-scope="{ $index }">
            <el-button
              size="mini"
              type="text"
              style="color: red"
              @click="handleDelete($index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- v-show="total > 0" -->
      <!-- <pagination
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> -->
    </div>

    <!-- 支付信息 -->
    <div class="app-box-nav">
      <el-form :model="queryParams" ref="payquerys" size="small" :inline="true">
        <div class="box">
          <div class="title">
            <div class="list">支付信息</div>
          </div>
          <div></div>
        </div>
      </el-form>

      <div>
        <el-form
          :model="settleAccountsPayTotalData"
          ref="orderpayForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="订单金额:">
                <el-input
                  v-model="settleAccountsPayTotalData.a"
                  placeholder="请输入订单金额"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="优惠金额:">
                <el-input
                  v-model="settleAccountsPayTotalData.b"
                  placeholder="请输入优惠金额"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="抵扣金额:">
                <el-input
                  v-model="settleAccountsPayTotalData.c"
                  placeholder="请输入抵扣金额"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="应收金额:">
                <el-input
                  v-model="settleAccountsPayTotalData.d"
                  placeholder="请输入应收金额"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="团购优惠:">
                <el-input
                  v-model="settleAccountsPayTotalData.k"
                  placeholder="请输入团购优惠"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-input v-model="OrderRuleForm.price"></el-input> -->
        </el-form>
      </div>
    </div>

    <!-- 收款方式 -->
    <div class="app-box-nav">
      <div class="box">
        <div class="title">
          <div class="list">收款方式</div>
        </div>
      </div>

      <div>
        <el-form
          :model="payWayForm"
          :rules="PayWayRules"
          ref="payWay"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="现金收款:" prop="moneyRmb">
                <el-input-number
                  v-model="queryParams.moneyRmb"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  class="w-300 text-left"
                  placeholder="请输入金额"
                  @focus="focusSumprice('moneyRmb')"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="微信收款:" prop="moneyWx">
                <el-input-number
                  v-model="queryParams.moneyWx"
                  placeholder="请输入金额"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  class="w-300 text-left"
                  @focus="focusSumprice('moneyWx')"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付宝收款:" prop="moneyZfb">
                <el-input-number
                  class="w-300 text-left"
                  v-model="queryParams.moneyZfb"
                  placeholder="请输入金额"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  @focus="focusSumprice('moneyZfb')"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="POS收款:" prop="moneyPos">
                <el-input-number
                  class="w-300 text-left"
                  v-model="queryParams.moneyPos"
                  placeholder="请输入金额"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  @focus="focusSumprice('moneyPos')"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item label="余额收款:" prop="moneyMember">
                <div class="BalanceCollect">
                  <div>
                    <el-select
                      class="w-300 text-left"
                      v-model="queryParams.cardIds"
                      placeholder="请选择会员卡"
                      multiple
                      filterable
                    >
                      <el-option
                        v-for="item in MemberCardList"
                        :key="item.id"
                        :label="item.cardName + ' - ' + '余额:' + item.balance"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </div>
                  <div class="Balance">
                    <el-input-number
                      class="w-300 text-left"
                      v-model="queryParams.moneyMember"
                      placeholder="请输入金额"
                      :precision="2"
                      :step="0.1"
                      :min="0"
                      :controls="false"
                      @focus="focusSumprice('moneyMember')"
                    ></el-input-number>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="团购实付:" prop="moneyChannelReal">
                <el-input-number
                  v-model="queryParams.moneyChannelReal"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  class="w-100 text-left"
                  disabled
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 新增消费 -->
    <consume
      ref="consume"
      @addConsume="addConsume"
      filterUser="filterUser"
    ></consume>

    <!-- 添加房间 -->
    <el-dialog
      title="选择房间"
      :visible.sync="AddroomdialogVisible"
      width="30%"
      :before-close="AddRoomhandleClose"
    >
      <span>
        <el-form ref="SelectRoom" :rules="SelectFormRules" :model="SelectRoom">
          <el-form-item prop="roomId" label="选择房间">
            <el-select
              class="w-100"
              v-model="SelectRoom.roomId"
              placeholder="请选择房间"
            >
              <el-option
                v-for="item in cKroomList"
                :key="item.roomId"
                :label="item.name"
                :value="item.roomId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRoomhandleClose">取 消</el-button>
        <el-button type="primary" @click="RoomSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 上下钟时间 -->
    <el-dialog
      :title="Timetype === 0 ? '请选择上钟时间' : '请选择下钟时间'"
      :visible.sync="TimedialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        <el-date-picker
          class="w-100"
          v-model="timeValue.value"
          type="datetime"
          :placeholder="Timetype === 0 ? '请选择上钟时间' : '请选择下钟时间'"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="saveItemTime">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 优惠 -->
    <addPre ref="PreInfo" @AddPre="AddPre"></addPre>

    <!-- 消费房间 -->
    <el-dialog
      title="消费房间"
      :visible.sync="consumedialogVisible"
      width="720px"
      :before-close="ConsumehandleClose"
    >
      <span>
        <el-form
          :model="dynamicValidateForm"
          :rules="ConsumeRules"
          ref="ConsumeRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row
            :gutter="24"
            :key="domain.key"
            v-for="(domain, index) in dynamicValidateForm.domains"
          >
            <el-col :span="10">
              <el-form-item
                :label="'房间' + (index + 1)"
                :key="domain.key"
                :prop="'domains.' + index + '.roomId'"
                :rules="{
                  required: true,
                  message: '房间不能为空',
                  trigger: 'blur',
                }"
              >
                <div class="newAdd">
                  <el-select
                    v-model="domain.roomId"
                    placeholder="请选择消费房间"
                    class="w-100"
                    filterable
                  >
                    <el-option
                      v-for="item in roomList"
                      :key="item.roomId"
                      :label="item.name"
                      :value="item.roomId"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="10">
              <el-form-item
                :label="'人数'"
                :key="domain.key"
                :prop="'domains.' + index + '.custCount'"
                :rules="{
                  required: true,
                  message: '人数不能为空',
                  trigger: 'blur',
                }"
              >
                <el-input-number
                  class="w-100"
                  v-model="domain.custCount"
                  :controls="false"
                  :precision="0"
                  :min="0"
                ></el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <i
                class="el-icon-circle-plus-outline addBtns"
                @click="addDomain"
              ></i>
              <i
                class="el-icon-remove-outline deleBtns"
                v-if="dynamicValidateForm.domains.length > 1"
                @click="removeDomain(domain)"
              ></i>
            </el-col>
          </el-row>
          <!-- </el-row> -->
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ConsumehandleClose">取 消</el-button>
        <el-button type="primary" @click="SaveConsume">确 定</el-button>
      </span>
    </el-dialog>

    <div class="botBtn">
      <el-button class="cancleBtn" @click="Cancle">取消</el-button>
      <el-button class="SaveBtn" @click="Save">保存</el-button>
    </div>
  </div>
</template>

<script>
// import {
//   getCreateWorkSpace,
//   deleteWorkPlace,
//   UpdateWorkPlace,
// } from "@/api/personnelManger/manger";
import { getRecording } from "@/api/business/order";
import {
  getStoreRoom,
  getMemberCard,
  getCanMemberCard,
  getSelectData,
} from "@/api/business/BusinessIndex";

import { storeAvailable, getStoreUser } from "@/api/business/client";
import consume from "@/components/business/consume";
import addPre from "@/components/AddPre/addPre";

// import { getStudyStatistics } from "@/api/bpm/setting";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { CommonStatusEnum } from "@/utils/constants";
import { getDictDatas, DICT_TYPE } from "@/utils/dict";

export default {
  name: "Dept",
  components: { consume, addPre },
  data() {
    return {
      // 部门列表
      deptOptions: [], // 部门属性结构
      depts: [], // 部门列表

      SumPrice: 0,
      storeWayOptions: [],
      custTypeOptions: [],
      settleAccountsPayTotalData: {
        a: "0.00", //  订单金额
        b: "0.00", // 优惠金额
        c: "0.00", // 抵扣金额,
        d: "0.00", // 应收金额
        k: "0.00", // 团购优惠
      },

      TimedialogVisible: false, // 上下钟时间
      AddroomdialogVisible: false, // 添加房间
      Timetype: "",
      timeValue: {
        index: "",
        value: "",
      },
      OrderRuleForm: {}, // 订单信息

      PreRuleForm: {
        name: "",
      }, // 优惠
      payWayForm: {}, // 收款方式
      ClientOptions: [], // 客户列表
      newConsumedialogVisible: false, // 新增消费
      consumedialogVisible: false, // 消费房间

      ConsumeRuleForm: {},
      getStatus: [],
      title: "",
      value1: "",
      options: [],
      value: "",
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 新增工作地点列表
      createList: [],
      // 部门树选项
      deptOptions: [],
      // 用户下拉列表
      users: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        cardIds: [], // 支付卡id集合
        roomParamsStr: "",
        custId: "",
        moneyMember: 0,
        moneyPos: 0,
        moneyRmb: 0,
        moneyWx: 0,
        moneyZfb: 0,
        orderClose: "",
        receiveUserId: "",
        orderOpen: "",
        orderRoomClose: "",
        roomName: "",
        recordingServiceList: [],
        roomParams: [],
        custType: "",
        inStoreType: "",
        moneyChannelReal: "",
      },
      total: 0,

      SelectFormRules: {
        roomId: { required: true, message: "请选择房间", trigger: "change" },
      },

      SelectRoom: {
        roomId: "",
        roomName: "",
      },

      PayruleForm: {
        price: "",
      },

      preTypeList: [
        {
          value: "C",
          label: "次卡优惠",
        },
        {
          value: "P",
          label: "百分比优惠",
        },
        {
          value: "M",
          label: "金额优惠",
        },
      ],

      options: [
        {
          value: "选项1",
          label: "黄金糕",
        },
        {
          value: "选项2",
          label: "双皮奶",
        },
      ],

      dynamicValidateForm: {
        domains: [
          {
            custCount: "",
            roomId: "",
          },
        ],
      },

      value: "",
      contentTypeObj: {
        I: "项目",
        P: "商品",
      },
      // 表单校验

      BasicRules: {
        // custId: [
        //   { required: true, message: "请选择消费客户", trigger: "blur" },
        // ],
        receiveUserId: [
          { required: true, message: "请选择开房员工", trigger: "blur" },
        ],
        orderOpen: [
          { required: true, message: "请选择创建时间", trigger: "blur" },
        ],
        orderClose: [
          { required: true, message: "请选择创建时间", trigger: "blur" },
        ],
        orderRoomClose: [
          { required: true, message: "选择结账时间", trigger: "blur" },
        ],
        inStoreType: [
          { required: true, message: "请选择进店方式", trigger: "blur" },
        ],
        custType: [
          { required: true, message: "请选择客户类型", trigger: "blur" },
        ],
        roomParamsStr: [
          { required: true, message: "请选择消费房间", trigger: "change" },
        ],
      },

      rules: {
        name: [{ required: true, message: "请输入工作地点", trigger: "blur" }],
        cityCode: [
          { required: true, message: "请选择工作地区", trigger: "blur" },
        ],
      },

      Payrules: {
        price: [{ required: true, message: "请输入订单金额", trigger: "blur" }],
      },

      // 消费房间
      ConsumeRules: {},

      // 收款方式
      PayWayRules: {
        price: [{ required: true, message: "请输入订单金额", trigger: "blur" }],
      },

      // 枚举
      CommonStatusEnum: CommonStatusEnum,
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS),
      seachUserClientTimeout: false,

      storeUser: [], // 待客员工
      storeUserLoading: false,

      roomList: [],
      roomObj: {}, // 通过房间id key
      cKroomList: [], // 已选择房间集合

      MemberCardList: [], // 卡包
    };
  },
  created() {
    this.getList();
    this.getOpenUser();
    this.getRoomList();
    this.getSelectStoreType();
    this.getSelectCustType();
  },

  watch: {
    "queryParams.recordingServiceList": {
      handler: function (newVal, oldVal) {
        console.log("a", newVal);
        let a = 0;
        let b = 0;
        let c = 0;
        let k = 0;
        let moneyChannelReal = 0;
        for (let i = 0; i < newVal.length; i++) {
          let Item = newVal[i];
          // 小计
          a += Number(Item.serverPriceSum);

          if (Item.preType === "P" || Item.preType === "M") {
            b += Number(Item.preMoney);
          }

          if (Item.preType === "C") {
            c += Number(Item.preMoney);
          }

          if (Item.preType === "L") {
            k += Number(Item.preMoney);
            moneyChannelReal += Number(Item.realMoney);
          }
        }

        this.settleAccountsPayTotalData.a = a.toFixed(2);
        this.settleAccountsPayTotalData.b = b.toFixed(2);
        this.settleAccountsPayTotalData.c = c.toFixed(2);
        this.settleAccountsPayTotalData.k = k.toFixed(2);

        this.settleAccountsPayTotalData.d = (a - b - c - k).toFixed(2);
        console.log(moneyChannelReal);
        this.queryParams.moneyChannelReal = moneyChannelReal.toFixed(2);
      },
      deep: true,
    },

    "settleAccountsPayTotalData.d": {
      handler(newVal, oldVal) {
        this.queryParams.moneyRmb = 0;
        this.queryParams.moneyWx = 0;
        this.queryParams.moneyZfb = 0;
        this.queryParams.moneyPos = 0;
        this.queryParams.moneyMember = 0;
      },
      deep: true,
    },

    "queryParams.roomParams": {
      handler: function (newVal, oldVal) {
        // console.log(newVal, oldVal);
        let roomParamsStr = [];
        for (let i = 0; i < newVal.length; i++) {
          let Item = newVal[i];
          let Rooms = this.roomObj[Item.roomId];
          console.log(Rooms);
          roomParamsStr.push(Rooms.name + " - " + Item.custCount);
        }

        this.queryParams.roomParamsStr = roomParamsStr.join(",");
        this.changeRoomList();
      },
      deep: true,
    },
  },
  methods: {
    focusSumprice(price) {
      const {
        moneyRmb,
        moneyWx,
        moneyZfb,
        moneyPos,
        moneyMember,
        moneyChannelReal,
      } = this.queryParams;
      let obj = {
        moneyRmb,
        moneyWx,
        moneyZfb,
        moneyPos,
        moneyMember,
        moneyChannelReal,
      };
      delete obj[price];

      let sumPrices = 0;
      for (let keys in obj) {
        let key = obj[keys];
        console.log(key);
        if (!!key) {
          sumPrices += key;
        }
      }
      this.queryParams[price] = Number(
        (this.settleAccountsPayTotalData.d - sumPrices).toFixed(2)
      );
    },

    // 进店方式
    getSelectStoreType() {
      getSelectData({ dictType: "OrderInStoreType" })
        .then((res) => {
          const { code, data } = res;
          if (code === 0) {
            this.storeWayOptions = data;
          }
        })
        .catch((err) => {});
    },

    // 客户类型
    getSelectCustType() {
      getSelectData({ dictType: "OrderCustType" })
        .then((res) => {
          const { code, data } = res;
          if (code === 0) {
            this.custTypeOptions = data;
          }
        })
        .catch((err) => {});
    },

    ConsumehandleClose() {
      this.$nextTick(() => {
        this.consumedialogVisible = false;
      });
    },
    // 消费房间
    ConsumeRoom() {
      this.consumedialogVisible = true;
    },

    // 消费房间 确定
    SaveConsume() {
      this.$refs["ConsumeRuleForm"].validate((valid) => {
        if (valid) {
          const { domains } = this.dynamicValidateForm;
          this.queryParams.roomParams = JSON.parse(JSON.stringify(domains));
          this.$nextTick(() => {
            this.ConsumehandleClose();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 删除 新增消费房间
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },

    // 新增
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: "",
        key: Date.now(),
      });
    },

    remoteMethod(query) {
      if (query !== "") {
        clearTimeout(this.seachUserClientTimeout);
        this.seachUserClientTimeout = setTimeout(() => {
          this.GetClientList(query);
        }, 500);
      } else {
        this.options = [];
      }
    },

    SelectCustomer() {
      this.queryParams.cardIds = [];
      this.getClinerCard(this.queryParams.custId);
    },

    // 获取用户卡包
    getClinerCard(custId) {
      this.clinerCardLoading = true;

      if (!custId) {
        this.$message.error("客户信息不能为空");
        return false;
      }

      getCanMemberCard({ customerId: custId })
        .then((res) => {
          this.clinerCardLoading = false;
          const { code, data } = res;
          if (code === 0) {
            let NewArry = [];
            if (data.length > 0) {
              // const { storesItem } = this.userInfo;

              for (let i = 0; i < data.length; i++) {
                let Item = data[i];
                // if (Item.storeId === storesItem.id) {
                //   this.isHaveCard = true;
                //   Item.haveCard = true;
                // }

                Item.active = false;

                NewArry.push(Item);
              }
            }
            this.MemberCardList = NewArry;
          }
        })
        .catch((err) => {
          this.clinerCardLoading = false;
        });
    },

    AddRoomhandleClose() {
      this.resetForm("SelectRoom");
      this.$nextTick(() => {
        this.AddroomdialogVisible = false;
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 选择房间 确定
    RoomSave() {
      this.$refs["SelectRoom"].validate((valid) => {
        if (valid) {
          const { index, roomId } = this.SelectRoom;
          if (!!this.roomObj[roomId]) {
            const { name } = this.roomObj[roomId];
            this.$set(
              this.queryParams.recordingServiceList[index],
              "roomId",
              roomId
            );

            this.$set(
              this.queryParams.recordingServiceList[index],
              "name",
              name
            );
          }
          console.log(this.queryParams.recordingServiceList[index]);
          console.log(this.roomObj[roomId]);
          this.AddRoomhandleClose();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    getRoomList() {
      this.roomLoading = true;
      getStoreRoom(this.queryParams)
        .then((res) => {
          // console.log(res);
          this.roomLoading = false;
          const { code, data } = res;
          if (code === 0) {
            this.roomList = data;
            for (let i = 0; i < data.length; i++) {
              let Item = data[i];
              this.roomObj[Item.roomId] = Item;
            }
          }
        })
        .catch((err) => {
          this.roomLoading = false;
        });
    },

    // 待客员工
    getOpenUser() {
      this.storeUserLoading = true;
      getStoreUser({ labelCode: "R" })
        .then((res) => {
          console.log(res);
          this.storeUserLoading = false;
          const { code, data } = res;
          if (code === 0) {
            this.storeUser = data;
          }
        })
        .catch((err) => {
          this.storeUserLoading = false;
        });
    },

    getsellUserId() {
      getStoreUser({})
        .then((res) => {
          const { code, data } = res;
          if (code === 0) {
            this.sellUserIdList = data;
          }
        })
        .catch((err) => {});
    },
    AddPre(res) {
      const { obj, index } = res;

      this.$set(
        this.queryParams.recordingServiceList[index],
        "realMoney",
        obj.realMoney
      );

      this.$set(
        this.queryParams.recordingServiceList[index],
        "preMoney",
        obj.preMoney
      );

      this.$set(
        this.queryParams.recordingServiceList[index],
        "moneyCardCount",
        obj.moneyCardCount
      );
      this.$set(
        this.queryParams.recordingServiceList[index],
        "moneyCardId",
        obj.moneyCardId
      );

      this.$set(
        this.queryParams.recordingServiceList[index],
        "preType",
        obj.preType
      );

      this.$set(
        this.queryParams.recordingServiceList[index],
        "moneyChannelReal",
        obj.moneyChannelReal
      );

      this.$set(this.queryParams.recordingServiceList[index], "isYh", obj.isYh);
      this.$set(
        this.queryParams.recordingServiceList[index],
        "minorCardNoList",
        !!obj.minorCardNoList ? this.getMinorCardNo(obj.minorCardNoList) : []
      );
    },

    getMinorCardNo(list) {
      return list.map((item) => {
        return item.value;
      });
    },

    // 添加优惠
    preferentialItemOpen(row, index) {
      this.$refs.PreInfo.preferentialItemOpen(row, index);
    },

    AddUpTimer(index) {
      this.Timetype = 0;
      this.TimedialogVisible = true;
      this.timeValue = {
        index: index,
        value: "",
      };
    },
    AddDownTimer(index) {
      this.Timetype = 1;
      this.TimedialogVisible = true;
      this.timeValue = {
        index: index,
        value: "",
      };
    },

    handleClose() {
      this.timeValue = {
        index: "",
        value: "",
      };
      this.TimedialogVisible = false;
    },

    saveItemTime() {
      const { index, value } = this.timeValue;
      if (!value) {
        this.$message.warning("请选择时间");
        return false;
      }

      if (this.Timetype === 0) {
        this.queryParams.recordingServiceList[index].clockTimeUp = value;
      } else if (this.Timetype === 1) {
        this.queryParams.recordingServiceList[index].clockTimeDown = value;
      }

      this.handleClose();
    },

    getAllMoneyCard() {
      this.moneyCardLoading = true;
      getMinorCardListByItemId({
        itemId: this.preferentialItemObj.itemId,
      })
        .then((res) => {
          this.moneyCardLoading = false;
          const { code, data } = res;
          if (code === 0) {
            this.moneyCardArry = data;
          }
        })
        .catch((err) => {
          this.moneyCardLoading = false;
        });
    },

    changeRoomList() {
      const { roomParams, recordingServiceList } = this.queryParams;
      let roomParamsList = roomParams.map((item) => {
        return item.roomId;
      });
      for (let i = 0; i < recordingServiceList.length; i++) {
        let item = recordingServiceList[i];
        if (!roomParamsList.includes(item.roomId) && !!item.roomId) {
          this.handleDelete(i);
        }
      }
    },

    AddRoom(index) {
      this.AddroomdialogVisible = true;
      let cKroomList = [];

      for (let i = 0; i < this.queryParams.roomParams.length; i++) {
        const item = this.queryParams.roomParams[i];
        cKroomList.push(this.roomObj[item.roomId]);
      }
      this.cKroomList = cKroomList;
      this.SelectRoom.index = index;
    },

    // 保存  订单录入
    Save() {

      this.$refs["queryParams"].validate((valid) => {
        if (valid) {
          //   alert("submit!");

          const { recordingServiceList } = this.queryParams;
          const errItem = [];

          for (let index = 0; index < recordingServiceList.length; index++) {
            const element = recordingServiceList[index];
            if (element.roomId === "" || element.roomId === undefined) {
              errItem.push(index + 1);
            }
          }
          if (errItem.length > 0) {
            this.$message.error("请补全第" + errItem + "条消费关联的房间");
            return false;
          }

          getRecording(this.queryParams)
            .then((res) => {
              const { code } = res;
              if (code === 0) {
                this.$router.go(-1);
                this.$message.success("操作成功");
              }
            })
            .catch((err) => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    Cancle() {
      this.$router.go(-1);
    },

    remoteMethod(query) {
      if (query !== "") {
        clearTimeout(this.seachUserClientTimeout);
        this.seachUserClientTimeout = setTimeout(() => {
          this.GetClientList(query);
        }, 500);
      } else {
        this.options = [];
      }
    },

    GetClientList(query) {
      storeAvailable({
        keyword: query,
      })
        .then((res) => {
          const { code, data } = res;
          if (code === 0) {
            this.ClientOptions = data;
          }
        })
        .catch((err) => {});
    },

    /** 查询培训报表 */
    getList() {
      //   this.loading = true;
      //   let queryParams = JSON.parse(JSON.stringify(this.queryParams));
      //   if (!!queryParams.time && queryParams.time.length > 0) {
      //     queryParams.startTime = queryParams.time[0];
      //     queryParams.endTime = queryParams.time[1];
      //   }
      //   queryParams.time = undefined;
      //   getStudyStatistics(queryParams)
      //     .then((response) => {
      //       const { code, data } = response;
      //       if (code === 0) {
      //         this.deptList = data.list;
      //         this.total = data.total;
      //       }
      //       console.log(response);
      //       this.loading = false;
      //     })
      //     .catch(() => {
      //       this.loading = false;
      //     });
    },

    // 新增消费
    New() {
      this.newConsumedialogVisible = true;
      this.$refs.consume.openAdddGood();
    },

    addConsume(res) {
      const { serverList } = res;
      for (let i = 0; i < serverList.length; i++) {
        let Item = serverList[i];
        this.queryParams.recordingServiceList.push({
          clockTimeDown: "",
          clockTimeUp: "",
          clockType: Item.clockType,
          contentCount: Item.contentCount,
          contentId: Item.contentId,
          contentType: Item.contentType,
          contentName: Item.contentName,
          userName: Item.userName,
          serverPriceSum: (
            Number(Item.price) * Number(Item.contentCount)
          ).toFixed(2),
          minorCardNo: "",
          moneyCardCount: "",
          moneyCardId: "",
          preMoney: "",
          preType: "",
          roomId: "",
          sellUserId: "",
          userId: Item.userId,
          price: Item.price,

          roomName: "",
          techicanName: "",
          total: Item.total,
        });
      }
      console.log(serverList);
    },

    // 格式化部门的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },

    // 创建
    getCreateWorkSpace() {
      //   getCreateWorkSpace(this.form)
      //     .then((response) => {
      //       const { code, data } = response;
      //       //this.loading = false;
      //       if (code === 0) {
      //         this.cancle();
      //         this.getList();
      //       }
      //       console.log(response);
      //     })
      //     .catch(() => {
      //       this.loading = false;
      //     });
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 用户昵称展示
    userNicknameFormat(row, column) {
      if (!row.leaderUserId) {
        return "未设置";
      }
      for (const user of this.users) {
        if (row.leaderUserId === user.id) {
          return user.nickname;
        }
      }
      return "未知【" + row.leaderUserId + "】";
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        name: undefined,
        sort: undefined,
        leaderUserId: undefined,
        phone: undefined,
        email: undefined,
        status: CommonStatusEnum.ENABLE,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.custId = "";
      this.queryParams.orderOpen = "";
      this.queryParams.orderRoomClose = "";
      this.queryParams.receiveUserId = "";
      this.handleQuery();
    },

    // /** 新增按钮操作 */
    // handleAdd(row) {
    //   // this.getProvince();
    //   this.form = {};
    //   this.open = true;
    //   this.title = "新增工作地点";
    // },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },

    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.open = true;
    //   this.title = "编辑工作地点";
    //   // this.reset();
    //   this.form = row;
    //   this.form = JSON.parse(JSON.stringify(row));
    // },

    cancle() {
      this.$refs["form"].resetFields();
      this.$nextTick(() => {
        this.open = false;
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      //   this.$refs["form"].validate((valid) => {
      //     console.log(valid);
      //     if (valid) {
      //       if (!!this.form.id) {
      //         UpdateWorkPlace(this.form).then((response) => {
      //           console.log("!!!==>", response);
      //           this.$modal.msgSuccess("修改成功");
      //           this.open = false;
      //           this.getList();
      //           if (code === 0) {
      //             this.cancle();
      //             this.getList();
      //           }
      //         });
      //       } else {
      //         this.getCreateWorkSpace();
      //       }
      //     }
      //   });
    },

    /** 删除按钮操作 */
    handleDelete(index) {
      this.queryParams.recordingServiceList.splice(index, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
.app-main {
  background-color: #f7f8fa;
}

.app-container {
  .search-box-nav {
    background: #ffffff;
    border-radius: 2px;
    margin: 24px;
    .title {
      height: 59px;
      font-size: 16px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
      line-height: 59px;
      font-weight: bold;
      padding-left: 24px;
    }
    .search-box-form {
      //   padding-top: 20px;
      position: relative;
      .form-nav {
        .search_row {
          display: flex;
          // padding-bottom: 50px;
          padding: 24px;

          .search_col {
            margin-left: 64px;
            &:first-child {
              margin-left: 24px;
            }
          }

          .search_date {
            display: flex;
            justify-content: space-between;
            margin-left: 24px;
            span {
              padding-left: 12px;
              padding-right: 12px;
              padding-top: 10px;
              display: block;
              font-size: 14px;
              font-weight: 400;
              color: rgba(0, 0, 0, 0.85);
            }
          }

          .btn {
            position: absolute;
            top: 55px;
            right: 24px;
            .btn_box {
              .repeat {
                margin-left: 16px;
              }
            }
          }
        }
      }
      .w-120 {
        width: 120px !important;
      }
      .content {
        padding: 0 48px;
      }
      .year {
        margin-left: 15px;
      }
    }
  }
  // margin: 20px;
  .app-box-nav {
    margin: 24px;
    background-color: #fff;
    padding: 24px;
    .addConsumption {
      width: 70px;
      height: 30px;
      line-height: 30px;
      border: 1px solid #4089fe;
      text-align: center;
      border-radius: 5px;
      padding: 0px 5px;
      color: #4089fe;
      margin-left: 15px;
      margin-top: -5px;
    }
  }
  padding: 0px;
  .top_nav {
    width: 100%;
    height: 44px;
    background: #ffffff;
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    .Learning {
      width: 99px;
      height: 22px;
      font-size: 14px;
      font-weight: 500;
      line-height: 22px;
      margin-left: 39px;
      color: rgba(0, 0, 0, 0.65);
    }
    .Closed {
      width: 79px;
      height: 22px;
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      line-height: 22px;
      margin-left: 45px;
    }
  }
  .box {
    display: flex;
    justify-content: space-between;
  }

  .title {
    display: flex;
    .list {
      font-size: 16px;
      font-weight: 700;
      margin-bottom: 20px;
    }
  }
}

.tree-width {
  width: 200px;
}

.BalanceCollect {
  display: flex;
  .Balance {
    margin-left: 20px;
  }
}

.botBtn {
  margin-bottom: 20px;
  margin-left: 700px;
  .SaveBtn {
    background-color: #0052d9;
    color: #fff;
  }
}

.newAdd {
  display: flex;
}

.deleBtns {
  font-size: 25px;
}

.addBtns {
  font-size: 25px;
  margin-top: 5px;
  margin-right: 10px;
}
</style>
